<?php

namespace app\modules\admin\controllers;

use Yii;
use app\modules\admin\models\Qrcode;
use app\modules\admin\models\QrcodeSearch;
use yii\web\Controller;
use app\modules\admin\components\BaseAdminController;
use yii\web\NotFoundHttpException;
use app\components\Wechat;
use yii\filters\AccessControl;

/**
 * QrcodeController implements the CRUD actions for Qrcode model.
 */
class QrcodeController extends BaseAdminController
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'allow' => true,
                        'actions' => [],
                        'roles' => ['@'],
                    ],
                ],
            ],
        ];
    }

    /**
     * Lists all Qrcode models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new QrcodeSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Qrcode model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Qrcode model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Qrcode();
        
        // 获取最新的ID
        $scene_id = $model->getLastId() + 1;
        $model->scene_id = $scene_id;

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            
            // 判断二维码类型
            $type = $model->type; // 1 - 临时的整型 2 - 临时的字符串 3 - 永久的整型 4 - 永久的字符串
            if ($type == 1) {
                $data = [
                    'action_name' => 'QR_SCENE',
                    'expire_seconds' => $model->expire_seconds,
                    'action_info' => [
                        'scene' => [
                            'scene_id' => $model->scene_id,
                        ]
                    ]
                ];
            } elseif ($type == 2) {
                $data = [
                    'action_name' => 'QR_STR_SCENE',
                    'expire_seconds' => $model->expire_seconds,
                    'action_info' => [
                        'scene' => [
                            'scene_str' => $model->scene_str,
                        ]
                    ]
                ];
            } elseif ($type == 3) {
                $data = [
                    'action_name' => 'QR_LIMIT_SCENE',
                    'action_info' => [
                        'scene' => [
                            'scene_id' => $model->scene_id,
                        ]
                    ]
                ];
            } elseif ($type == 4) {
                $data = [
                    'action_name' => 'QR_LIMIT_STR_SCENE',
                    'action_info' => [
                        'scene' => [
                            'scene_str' => $model->scene_str,
                        ]
                    ]
                ];
            }
            // 调用微信API并且存储二维码信息
            $re = Wechat::qrcode_create($data);

            if ($re) {
                $model->ticket = $re['ticket'];
                $model->url = $re['url'];
                $model->save();
            }
            
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
                'scene_id' => $scene_id
            ]);
        }
    }

    /**
     * Updates an existing Qrcode model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing Qrcode model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    // 关联二维码列表
    public function actionMatch($relation)
    {
        $searchModel = new QrcodeSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        return $this->render('match', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    // 执行关联二维码数据库操作
    public function actionDoMatch()
    {
        // 获取所需要的字段
        $relation = Yii::$app->request->get('relation');
        $id_qrcode = Yii::$app->request->get('id_qrcode');
        if (empty($relation) || empty($id_qrcode)) {
            Yii::$app->session->setFlash('error', '请求错误');
            return $this->redirect(['wechat/list-img-articles']);
        }

        // 检查是否已经关联
        $qrcode = Qrcode::find()->where(['relation' => $relation])->one();
        if ($qrcode) {
            Yii::$app->session->setFlash('error', '当前资源已经关联到ID为 ' . $qrcode->id . ' 的二维码');
            return $this->redirect(['qrcode/view', 'id' => $qrcode->id]);
        } else {
            $qrcode = Qrcode::find()->where(['id' => $id_qrcode])->one();
            $qrcode->relation = $relation;
            $qrcode->save();
            Yii::$app->session->setFlash('success', '当前资源已成功经关联到ID为 ' . $qrcode->id . ' 的二维码');
        }

        return $this->redirect(['qrcode/index']);
    }

    /**
     * Finds the Qrcode model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return Qrcode the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Qrcode::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
